package cn.com.jslh.boarpro.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.net.CookieHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.jslh.boarpro.base.BaseApplication;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：周洲 on 2017/7/24 13:53
 * <p>
 * 邮箱：double0zhou@126.com
 */

public class WebService {
    public static String BaseUrl;
    public static String PACE;
    private ProgressDialog progressDialog;
    private boolean showDialog = false;

    public static void init(String BaseUrl, String Pace) {
        WebService.BaseUrl = BaseUrl;
        WebService.PACE = Pace;
    }

    private SoapObject soapObject;
    private String url;
    private Context context;
    private NetSuccessListener netSuccessListener;
    private NetFaildListener netFaildListener;

    public WebService(Builder builder) {
        this.soapObject = builder.soapObject;
        this.url = builder.postUrl;
        this.context = builder.context;
        this.netSuccessListener = builder.netSuccessListener;
        this.netFaildListener = builder.netFaildListener;
        this.showDialog = builder.showDialog;
        if (showDialog) {
            showDialog("loading...");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("url", this.url);
        map.put("soap", this.soapObject);
        Flowable.just(map)
                .map(new Function<Map<String, Object>, Result>() {
                    @Override
                    public Result apply(@NonNull Map<String, Object> o) throws Exception {
                        return getRemoteInfo(o.get("url").toString(), (SoapObject) o.get("soap"));
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result>() {
                    @Override
                    public void accept(@NonNull Result r) throws Exception {
                        if (showDialog) {
                            cancleDialog();
                        }
                        if (r == null)
                            return;
                        switch (r.code) {
                            case 0:
                                netSuccessListener.Success(r.msg);
                                break;
                            case 1:
                                if (r == null || r.msg == null || r.msg.equals(""))
                                    break;
                                if (netFaildListener != null)
                                    netFaildListener.Faild(r.msg);
                                else
                                    Log.d("打印message",r.msg);
                                    Toast.makeText(context, r.msg, Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });

    }

    /**
     * @return
     * @throws Exception
     */
    private static Result getRemoteInfo(String WSDL_URI, SoapObject request) throws Exception {
        //创建SoapSerializationEnvelope 对象，同时指定soap版本号(之前在wsdl中看到的)
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
        envelope.bodyOut = request;//由于是发送请求，所以是设置bodyOut
        envelope.dotNet = true;//由于是.net开发的webservice，所以这里要设置为true
        HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI, 20000); //10s超时
        SoapObject object;
        try {
            List headers = new ArrayList();
            headers.add(new HeaderProperty("urn:client", "WSContext"));
            headers.add(new HeaderProperty("SOAPAction", "SOAPAction"));
            headers.add(new HeaderProperty("SessionId", SPUtils.getInstance().getString(BaseApplication.EASSESSIONID)));
            for (Object header : headers) {
                HeaderProperty headerProperty1 = (HeaderProperty) header;
                String headerKey = headerProperty1.getKey();
                String headerValue = headerProperty1.getValue();
                Log.e("webservicestart", headerKey + ":" + headerValue);
            }

            List headerList = httpTransportSE.call(null, envelope, headers);//调用
//            if (envelope.bodyIn instanceof SoapFault) {
//                return new Result(1, "通讯异常");
//            }
//            if (envelope.bodyIn instanceof SoapFault) {
//                Log.e("webservice", ((SoapFault) envelope.bodyIn).faultstring);
//                return new Result(1, ((SoapFault) envelope.bodyIn).faultstring);
//            }
            BaseApplication.headerList = headerList;
            for (Object header : headerList) {
                HeaderProperty headerProperty = (HeaderProperty) header;
                String headerKey = headerProperty.getKey();
                String headerValue = headerProperty.getValue();
                Log.e("webservice", headerKey + ":" + headerValue);
            }
            // 获取返回的数据
            object = (SoapObject) envelope.bodyIn;
//            object= (SoapObject) envelope.getResponse();
        } catch (HttpResponseException ex) {
            return new Result(1, ex.getMessage());

        } catch (IOException ex) {
            return new Result(1, ex.getMessage());
        } catch (XmlPullParserException ex) {
            return new Result(1, ex.getMessage());
        } catch (Exception ex) {
            return new Result(1, ex.getMessage());
        }
        // 获取返回的结果
        String result = object.getProperty(0).toString();
        Log.d("webservice", result);
        if (result.startsWith("SoapFault")) {
            return new Result(1, result);
        } else if (result.contains("flag")) {
            return new Result(0, result);
        } else {
            return new Result(0, result);
        }
    }


    public void showDialog(String msg) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(context, ProgressDialog.STYLE_SPINNER);
        }
        progressDialog.setCancelable(false);
        progressDialog.setMessage(msg);
        progressDialog.show();
    }

    public void cancleDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    public interface NetSuccessListener {
        void Success(String s) throws JSONException;
    }

    public interface NetFaildListener {
        void Faild(String str);
    }

    public static class Result {
        private int code;
        private String msg;

        public Result(int code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    }

    public static class Builder {
        private SoapObject soapObject;
        private String postUrl;
        private Context context;
        private NetSuccessListener netSuccessListener;
        private NetFaildListener netFaildListener;
        private boolean showDialog;

        public Builder(Context context, String method, String space) {
            this.context = context;
//            String namespace = " http://192.168.0.153:6892/ormrpc/services/"+ space;//namespace  http://192.168.0.133:6888/ormrpc/services/WSPeiZhongFacade
            String namespace = " http://192.168.0.153:6892/ormrpc/services/" + space;
//        String methodName = methodname;//要调用的方法名称//"exportMuZhuData"
//            this.postUrl = namespace + "?wsdl";//wsdl 的uri http://192.168.0.153:6892/ormrpc/services/WSPeiZhongFacade?wsdl
            this.postUrl = BaseApplication.ServerUrl + space + "?wsdl";//wsdl 的uri http://192.168.0.153:6892/ormrpc/services/WSPeiZhongFacade?wsdl
               Log.d("打印postUrl",postUrl+"zxx")  ;
            this.soapObject = new SoapObject("urn:client", method);
        }

        public Builder showDialog(boolean showDialog) {
            this.showDialog = showDialog;
            return this;
        }

        public Builder addProperty(String key, Object value) {
            soapObject.addProperty(key, value);
            return this;
        }

        public Builder success(NetSuccessListener netSuccessListener) {
            this.netSuccessListener = netSuccessListener;
            return this;
        }

        public Builder faild(NetFaildListener netFaildListener) {
            this.netFaildListener = netFaildListener;
            return this;
        }

        public WebService post() {
            return new WebService(this);
        }
    }
}
